<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
<form onsubmit="return false">
    <label>
        <textarea name="message" style="height:300px;width:300px"></textarea>
    </label>
    <input onclick="send(this.form.message.value)" type="button" value="发送消息">
    <label>
        <textarea id="responseText" style="height:300px;width:300px"></textarea>
    </label>
    <input onclick="document.getElementById('responseText').value=''" type="button" value="清空内容">
</form>

<script>
    let webSocket
    //判断是否支持WebSocket
    if (window.WebSocket) {
        webSocket = new WebSocket("ws://localhost:8080/hello")

        //连接开启
        webSocket.onopen = function () {
            let rt = document.getElementById("responseText");
            rt.value = "连接开启"
        }

        //接收消息
        webSocket.onmessage = function (ev) {
            let rt = document.getElementById("responseText");
            rt.value = rt.value + "\n" + ev.data;
        }

        //连接关闭
        webSocket.onclose = function () {
            let rt = document.getElementById("responseText");
            rt.value = rt.value + "\n" + "连接关闭"
        }
    } else {
        alert("当前浏览器不支持WebSocket")
    }

    //发送消息
    function send(message) {
        //判断WebSocket是否开启
        if (webSocket.readyState === WebSocket.OPEN) {
            webSocket.send(message)
        } else {
            alert("连接未开启")
        }
    }
</script>
</body>

</html>